﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls;
using System.Net;
using KWS.SPWeather.MetOffice;

namespace KWS.SPWeather.SPWeatherWebPart
{
    /// <summary>
    /// Custom toolpart for Edit Webpart Properties.
    /// </summary>
    public class SPWeatherToolPart : ToolPart
    {
        Label lblAccountKey;
        TextBox txtAccountKey;
        Label lblSite;
        TextBox txtSite;
        LinkButton btnFindSite;
        Panel pnlSPWeather;
        Label lblMessage;

        /// <summary>
        /// Set the collapse title of the toolpart.
        /// </summary>
        public SPWeatherToolPart()
        {
            Title = "SPWeather";         
        }

        /// <summary>
        /// Public properties for the WebPart to set any existing values.
        /// </summary>
        public string SiteName { get; set; }
        public string AccountKey {get;set;}

        /// <summary>
        /// Create and render the custom properties
        /// </summary>
        protected override void CreateChildControls()
        {           
            pnlSPWeather = new Panel()
            {
                ID = "pnlSPWeather"
            };
            lblSite = new Label()
            {
                ID = "lblSite",
                Text = "Site:"
            };
            txtSite = new TextBox()
            {
                ID = "txtSite",
                Text = SiteName
            };
            lblAccountKey = new Label()
            {
                ID = "lblAccountKey",
                Text = "Account Key"                
            };
            txtAccountKey = new TextBox()
            {
                ID = "txtAccountKey",                
                ToolTip = "Azure data market Primary Account Key",
                Text = AccountKey
            };
            btnFindSite = new LinkButton()
            {
                ID = "btnFindSite",
                Text = "Find"
            };
            btnFindSite.Click += new EventHandler(btnFindSite_Click);
            lblMessage = new Label()
            {
                ID = "lblMessage"
            };

            Table table = new Table();
            table.Attributes.Add("Style", "width: 100%; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-collapse: collapse;");
            TableRow row = new TableRow();
            TableCell cell = new TableCell();
            Panel pnl = new Panel()
            {
                CssClass = "UserSectionHead"
            };
            pnl.Controls.Add(lblAccountKey);
            cell.Controls.Add(pnl);
            pnl = new Panel()
            {
                CssClass = "UserSectionBody"
            };
            Panel pnlUserControlGroup = new Panel()
            {
                CssClass = "UserControlGroup"
            };
            pnlUserControlGroup.Controls.Add(txtAccountKey);
            pnl.Controls.Add(pnlUserControlGroup);
            cell.Controls.Add(pnl);
            pnl = new Panel()
            {
                CssClass = "UserDottedLine"
            };
            cell.Controls.Add(pnl);
            row.Controls.Add(cell);
            table.Rows.Add(row);

            row = new TableRow();
            cell = new TableCell();
            pnl = new Panel()
            {
                CssClass = "UserSectionHead"
            };
            pnl.Controls.Add(lblSite);
            cell.Controls.Add(pnl);
            pnl = new Panel()
            {
                CssClass = "UserSectionBody"
            };
            pnlUserControlGroup = new Panel()
            {
                CssClass = "UserControlGroup"
            };
            pnlUserControlGroup.Controls.Add(txtSite);
            pnlUserControlGroup.Controls.Add(new Literal() { Text = "&nbsp;" });
            pnlUserControlGroup.Controls.Add(btnFindSite);
            pnlUserControlGroup.Controls.Add(new Literal() { Text = "<br/>" });
            pnlUserControlGroup.Controls.Add(lblMessage);
            pnl.Controls.Add(pnlUserControlGroup);
            cell.Controls.Add(pnl);
            row.Controls.Add(cell);
            table.Rows.Add(row);
           
            Controls.Add(table); 

            base.CreateChildControls();
        }

        /// <summary>
        /// Update the propeties in the main web part with the settings.
        /// </summary>
        public override void ApplyChanges()
        {
            SPWeatherWebPart wpSPWeather = (SPWeatherWebPart)this.ParentToolPane.SelectedWebPart;
            wpSPWeather.AccountKey = txtAccountKey.Text;
            wpSPWeather.SiteName = txtSite.Text;
        } 

        /// <summary>
        /// Query the Met Office data service to find the site.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnFindSite_Click(object sender, EventArgs e)
        {
            Uri serviceUri = new Uri("https://api.datamarket.azure.com/DataGovUK/MetOfficeWeatherOpenData/");
            DataGovUKMetOfficeWeatherOpenDataContainer metOffice = new DataGovUKMetOfficeWeatherOpenDataContainer(serviceUri);
            metOffice.Credentials = new NetworkCredential(txtAccountKey.Text, txtAccountKey.Text);
            //There's no way of querying for a site so I have to get all of them!

            try
            {
                int count = metOffice.Site.Count();
                var sites = metOffice.Site
                    .Take(count)
                    .ToList();
                var site = sites
                    .Where(s => s.Name.ToLower().StartsWith(txtSite.Text.ToLower()))
                    .FirstOrDefault();
                if (site != null)
                {
                    txtSite.Text = site.Name;
                }
            }
            catch (Exception ex)
            {
                lblMessage.Text = "There was a problem accessing the Met Office data.";
            }
        }



    }
}
